package com.cloud.rou.im.core.id;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class ConversionAlphaNumericUtil {
    /** The logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(ConversionAlphaNumericUtil.class);

    private static final String baseDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ[]";
    private static final int BASE = baseDigits.length();
    private static final char[] digitsChar = baseDigits.toCharArray();
    private static final int FAST_SIZE = 'z';
    private static final int[] digitsIndex = new int[FAST_SIZE + 1];

    static {
        for (int i = 0; i < FAST_SIZE; i++) {
            digitsIndex[i] = -1;
        }
        //
        for (int i = 0; i < BASE; i++) {
            digitsIndex[digitsChar[i]] = i;
        }
    }

    public static void main(String[] args) {
        System.out.println(encode(System.currentTimeMillis()));
        System.out.println(decode("rIa5sAt"));

    }
    public static long decode(String s) {
        long result = 0L;
        long multiplier = 1;
        for (int pos = s.length() - 1; pos >= 0; pos--) {
            int index = getIndex(s, pos);
            result += index * multiplier;
            multiplier *= BASE;
        }
        return result;
    }

    public static String encode(long number) {
        if (number < 0)
            LOGGER.error("Number(Base62) must be positive: " + number);
        if (number == 0)
            return "0";
        StringBuilder buf = new StringBuilder();
        while (number != 0) {
            buf.append(digitsChar[(int) (number % BASE)]);
            number /= BASE;
        }
        return buf.reverse().toString();
    }

    private static int getIndex(String s, int pos) {
        char c = s.charAt(pos);
        if (c > FAST_SIZE) {
            LOGGER.error("Unknow character for Base62: " + s);
        }
        int index = digitsIndex[c];
        if (index == -1) {
            LOGGER.error("Unknow character for Base62: " + s);
        }
        return index;
    }

}
